package com.b2c.erp.controller.fahuo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jakarta.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.b2c.common.utils.JsonUtil;
import com.b2c.entity.DataRow;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.interfaces.erp.ErpOrderService;
import com.b2c.interfaces.wms.ErpStockOutFormService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.erp.req.GeneratePickingReq;
import com.b2c.erp.response.ApiResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 描述：
 * 订单ajax
 *
 * @author qlp
 * @date 2019-06-03 16:30
 */
@RequestMapping(value = "/ajax_fahuo")
@RestController
public class AjaxPickGoodsController {

    @Autowired
    private ErpOrderService orderService;

    @Autowired
    private ErpUserActionLogService logService;
    @Autowired
    private ErpStockOutFormService stockOutFormService;


    Logger log = LoggerFactory.getLogger(AjaxPickGoodsController.class);

    /**
     * 按订单生成拣货单
     *
     * @return
     */
    @RequestMapping(value = "/generating_picking_list_by_order", method = RequestMethod.POST)
    public ApiResult<Long> joinPicking(@RequestBody GeneratePickingReq req , HttpServletRequest request) {
        log.info("AJAX生成拣货单"+ JSON.toJSONString(req));
        try {
            var result = orderService.generatingPickingListByOrder(req.getId());
            //添加系统日志
            logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Add,
                    "/order/order_wait_pick_list","生成拣货单 , id : "+JsonUtil.objToString(req.getId())+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");
            return new ApiResult<>(result.getCode(), result.getMsg(), result.getData());
        }catch (Exception e){
            return new ApiResult<>(EnumResultVo.Fail.getIndex(), e.getMessage());
        }

    }


    /**
     * 按订单items生成拣货单
     *
     * @return
     */
    @RequestMapping(value = "/generating_picking_list_by_order_items", method = RequestMethod.POST)
    public ApiResult<Long> generatingPickingListByOrderItems( @RequestBody DataRow data ,HttpServletRequest request) {
        log.info("AJAX生成拣货单(按orderItem)：{userName:"+request.getSession().getAttribute("userName")+"}");
        log.info("AJAX生成拣货单(按orderItem)"+ JSON.toJSONString(data));
        String orderItems = data.getString("orderItems");
        if(StringUtils.isEmpty(orderItems)) return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误，orderItem为空");
        List<Long> orderItemIds = new ArrayList<>();
        for (var itemId:orderItems.split(",")) {
            if(StringUtils.isEmpty(itemId)== false){
                orderItemIds.add(Long.parseLong(itemId));
            }
        }
        if(orderItemIds.size() == 0) return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误，orderItem为空");
        String s= "";
        try {

            var result = orderService.generatingPickingListByOrderItem(orderItemIds);
            if(result.getCode()  == EnumResultVo.SUCCESS.getIndex()){
                return new ApiResult<>(0, "",result.getData());
            }else{
                return new ApiResult<>(result.getCode(), result.getMsg());
            }
//            //添加系统日志
//            logService.addUserAction(
//                    Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Add,
//                    "/ajax_fahuo/generating_picking_list_by_order_items",""
//                    ,JSON.toJSONString(result)
//            );

        }catch (Exception e){
            return new ApiResult<>(EnumResultVo.Fail.getIndex(), e.getMessage());
        }

    }

    /**
     * 取消拣货
     * @param data
     * @param request
     * @return
     */
    @RequestMapping(value = "/picking_goods_cancel", method = RequestMethod.POST)
    public ApiResult<Integer> cancelPick( @RequestBody DataRow data , HttpServletRequest request) {
        log.info("AJAX取消拣货"+ JSON.toJSONString(data));
        if(StringUtils.isEmpty(data.getString("id")) || data.getLong("id") <= 0){
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误，缺少id");
        }
        Integer userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
        String userName = request.getSession().getAttribute("trueName").toString();
        var result = stockOutFormService.cancelStockOut(data.getLong("id"),userId,userName);

        if(result.getCode() == EnumResultVo.SUCCESS.getIndex()){
            return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS");
        }else
            return new ApiResult<>(result.getCode(), result.getMsg());
//        try {
//            var result = orderService.generatingPickingListByOrder(req.getId());
//            //添加系统日志
//            logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Add,
//                    "/order/order_wait_pick_list","生成拣货单 , id : "+JsonUtil.objToString(req.getId())+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");
//            return new ApiResult<>(result.getCode(), result.getMsg(), result.getData());
//        }catch (Exception e){
//            return new ApiResult<>(EnumResultVo.Fail.getIndex(), e.getMessage());
//        }

    }

}
